﻿/// -----------------------------------------------------------------------
/// (c) 2009 Microsoft Corporation -- All rights reserved
/// This code is licensed under the MS-PL
/// http://www.opensource.org/licenses/ms-pl.html
/// Courtesy of the Open Source Techology Center: http://port25.technet.com
/// -----------------------------------------------------------------------

using System.IO;
using System.Text;
using gsToolkit;

namespace SynthFastCGI {

    internal static class MessageExtensions {

        internal static void Write( this FileStream stream , Message msg) {
            byte[] buffer = msg.Buffer;
            stream.Write(buffer, 0, buffer.Length);
        }
    }

    internal class Message {
        private MemoryStream RequestBuffer;
        private byte[] buffer;
        public byte[] Buffer {
            get {
                if(buffer == null || buffer.Length != RequestBuffer.Length ) {
                    buffer = RequestBuffer.ToArray();
                    int length = buffer.Length - 8;

                    buffer[4] = (byte) (length/256);
                    buffer[5] = (byte) (length%256);
                    buffer.Debug();
                }
                return buffer;
            }

        }
        internal Message(byte MessageType, byte requestIdByte0, byte requestIdByte1 ) {
            RequestBuffer = new MemoryStream();

            RequestBuffer.WriteByte(FastCGI.FCGI_VERSION);
            RequestBuffer.WriteByte(MessageType);
            RequestBuffer.WriteByte(requestIdByte1); // requestID byte 1
            RequestBuffer.WriteByte(requestIdByte0); // requestID byte 0
            RequestBuffer.WriteByte(0); // contentLength byte 1
            RequestBuffer.WriteByte(0); // contentLength byte 0
            RequestBuffer.WriteByte(0); // paddingLength
            RequestBuffer.WriteByte(0); // reserved
        }

        internal void Append(byte p) {
            RequestBuffer.WriteByte(p);
        }

        internal void PadTo(int Length) {
            Length += 8; // account for 8 byte header.
            while( RequestBuffer.Length < Length)
                RequestBuffer.WriteByte(0);
        }

        internal void Append(string key,string value) {
            byte[] bufk = ASCIIEncoding.ASCII.GetBytes(key);
            byte[] bufv = ASCIIEncoding.ASCII.GetBytes(value);

            RequestBuffer.WriteByte((byte)bufk.Length);
            RequestBuffer.WriteByte((byte)bufv.Length);
            RequestBuffer.Write(bufk, 0, bufk.Length);
            RequestBuffer.Write(bufv, 0, bufv.Length);
        }

    }
}
